<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use \think\Loader;
use think\Session;
use think\Validate;

class User extends Controller
{
    public $session;

    public function _initialize()
    {
        parent::_initialize();
        $this->session = getSession();
    }

    /**
     * 首页
     */
    public function index()
    {
        return $this->fetch('login');
    }

    /**
     * 登录
     */
    public function login()
    {
        $post = $this->request->post();
        if (empty($post)) {
            $this->redirect('user/index');
        }
        $validate = validate('User');
        $validate->scene('login');
        $username = $post['username'];

        if (!$validate->check($post)) {
            $this->error($validate->getError());
        } else {
            $user = Db::name('user')
                ->where(['username' => $username, 'flag' => 1, 'status' => 1])
                ->find();
            if (!checkArr($user)) {
                $this->error('用户名错误');
            }
            if (md5($post['password']) !== $user['password']) {
                $this->error('密码错误');
            } else {
                //设置session
                session('username', $post['username']);
                session('user_id', $user['id']);
                session('super', $user['super']);
                session('pid', $user['pid']);
                session('role_id', $user['role_id']);
                session('from', $user['from']);
                session('company_id', $user['company_id']);
                session('type', $user['type']);
                session('truename', $user['truename']);

                Db::name('user')
                    ->where('username', $post['username'])
                    ->update(['last_login_ip' => $_SERVER['REMOTE_ADDR'], 'last_login_time' => date('Y-m-d H:i:s', time())]);
                $this->success('登陆成功', 'index/index');
            }
        }
    }

    /**
     * url登录
     */
    public function urlLogin()
    {
        $username = get('username');
        $user = Db::name('user')
            ->where(['username' => $username, 'flag' => 1, 'status' => 1])
            ->find();
        if (!checkArr($user)) {
            $this->error('用户名错误');
        }
        if (get('password') !== $user['password']) {
            $this->error('密码错误');
        } else {
            //设置session
            session('username', $username);
            session('truename', $user['truename']);
            session('user_id', $user['id']);
            session('super', $user['super']);
            session('pid', $user['pid']);
            session('role_id', $user['role_id']);
            session('from', $user['from']);
            session('company_id', $user['company_id']);
            session('type', $user['type']);
            session('truename', $user['truename']);
            Db::name('user')
                ->where('username', $username)
                ->update(['last_login_ip' => $_SERVER['REMOTE_ADDR'], 'last_login_time' => date('Y-m-d H:i:s', time())]);
            $this->success('登陆成功', 'index/index');
        }
    }

    //注销
    public function logOut()
    {
        session('username', null);
        $this->redirect('admin/user/index');
    }

    /**
     * 用户列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function userlist()
    {
        $where = array(
            'pid' => $this->session['user_id'],
            'flag' => 1
        );
        $search = $this->request->get('search');
        $search && $where['username'] = ['like', '%' . $search . '%'];
        $data = Db::name('User')
            ->where($where)
            ->order('id asc')
            ->paginate(12, false, ['query' =>
                [
                    'username' => $search
                ]]);
        $list = $data->all();
        if (checkArr($list)) {
            $company_ids = join(',', array_unique(array_column($list, 'company_id')));
            $companys = Db::name('company')->where('id in (' . $company_ids . ')')->select();
            if (count($companys) > 0) {
                foreach ($companys as $key => $value) {
                    $value['use_capacity'] > 0 && $companys[$key]['use_capacity'] = diskTransform($value['use_capacity']);
                }
            }
            $this->assign('companys', arrayCombine($companys, 'id'));
        }

        //获取当前用户创建的角色列表
        $auth_group = $this->getUserRole();
        checkArr($auth_group) && $auth_group = arrayCombine($auth_group, 'id');
        $this->assign('type', isession('type'));
        $this->assign('auth_group', $auth_group);
        $this->assign('users', $data);
        $this->assign('search', $search);
        return $this->fetch();
    }

    /**
     * 增加用户
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addUser()
    {
        if (post()) {
            $post = post();
            if ($post['concierge'] == 1) {
                empty($post['company']) && $this->error('当前角色下公司名不能为空');
                empty($post['upload_capacity']) && $this->error('当前角色下空间容量不能为空');
            }

            $validate = validate('User');
            $res = $validate->check($post);
            if ($res !== true) {
                $this->error($validate->getError());
            }
            $where['username'] = $post['username'];
            $where['flag'] = 1;
            $res = Db::name('user')
                ->where($where)
                ->find();
            if (checkArr($res)) {
                $this->error('该用户已存在');
            }

            $data['username'] = $post['username'];
            $data['truename'] = $post['truename'];
            $data['status'] = 1;
            $data['password'] = md5($post['password']);
            $data['email'] = $post['email'];
            $data['type'] = $post['type'];
            $data['last_login_ip'] = '0.0.0.0';
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $data['super'] = $this->session['super'] + 1;
            $data['pid'] = $this->session['user_id'];
            $data['role_id'] = $post['group_id'];
            $data['from'] = isset($this->session['from']) ? $this->session['from'] . "," . $this->session['user_id'] : $this->session['user_id'];
            $data['company_id'] = $this->session['company_id'];

            if (($this->session['type'] == 1) && (!empty($post['company'])) && ($post['concierge'] == 1)) {
                Db::name('company')->insert(['name' => $post['company'], 'upload_capacity' => $post['upload_capacity']]);
                $data['company_id'] = Db::name('company')->getLastInsID();
            }

            Db::name('user')->insert($data);
            $this->success('添加成功');
        } else {
            $this->assign('auth_group', $this->getUserRole());
            $this->assign('type', isession('type'));
            return $this->fetch('add');
        }

    }

    //编辑提交
    public function editUser($id)
    {
        if (post()) {
            $post = post();
            if ($post['id'] == 1 && $this->session['user_id'] !== 1) {
                $this->error('系统管理员无法修改');
            }
            $validate = validate('User');

            $where['username'] = $post['username'];
            $where['flag'] = 1;
            $where['id'] = ['neq', $post['id']];
            $res = Db::name('user')
                ->where($where)
                ->find();
            if (checkArr($res)) {
                $this->error('该用户已存在');
            }

            $updateData = array(
                'status' => $post['status'],
                'username' => $post['username'],
                'truename' => $post['truename'],
                'email' => $post['email'],
                'role_id' => $post['group_id']
            );
            if (empty($post['password']) && empty($post['check_password'])) {
                $res = $validate->scene('edit')->check($post);
                if ($res !== true) {
                    $this->error($validate->getError());
                }
                Db::name('user')
                    ->where('id', $post['id'])
                    ->update($updateData);
            } else {
                $res = $validate->scene('editPassword')->check($post);
                if ($res !== true) {
                    $this->error($validate->getError());
                }
                $updateData['password'] = md5($post['password']);
                Db::name('user')->where('id', $post['id'])->update($updateData);
            }

            //更新公司信息
            if (!empty($post['company'])) {
                Db::name('company')
                    ->where('id', $post['company_id'])
                    ->update(['name' => $post['company'], 'upload_capacity' => $post['upload_capacity']]);
            }

            //禁用用户添加登录日志
            if ($post['status'] == 2) {
                $insertData = array(
                    'uid' => $post['id'],
                    'uname' => $post['username'],
                    'login_time' => time(),
                    'login_ip' => '#127.0.0.1'
                );
                DB::name('user_log')->insert($insertData);
            }

            $this->success('编辑成功');
        } else {
            $data = Db::name('User')
                ->where('id', $id)
                ->find();

            if ($data['company_id'] != 0) {
                $company = Db::name('company')->where(['id' => $data['company_id']])->find();
                $this->assign('company', $company);
            }

            $this->assign('auth_group', $this->getUserRole());
            $this->assign('type', $this->session['type']);
            $this->assign('data', $data);
            return $this->fetch('edit');
        }

    }

    //删除用户
    public function deleteUser()
    {
        $id = ipost('id');
        if ($id === 1) {
            $this->error('超级管理员无法删除');
        }

        $where = array('id' => $id, 'pid' => $this->session['user_id']);
        $res = Db::name('user')
            ->where($where)
            ->update(['flag' => 2, 'role_id' => 0]);
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 获取当前用户下的角色
     * @param array $data
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getUserRole()
    {
        if ($this->session['user_id'] == 1) {//总公司
            $where['company_id'] = $this->session['company_id'];
        }
        $where['creater_id'] = $this->session['user_id'];
        $where['id'] = ['neq', $this->session['role_id']];
        $where['flag'] = 1;
        $where['status'] = 1;
        return Db::name('auth_group')->where($where)->order('sort asc')->select();
    }

    /**
     * 个人中心
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function info()
    {
        if (post()) {
            $post = post();
            if ($post['id'] == 1 && $this->session['user_id'] !== 1) {
                $this->error('系统管理员无法修改');
            }

            if (empty($post['password']) && empty($post['check_password'])) {

                Db::name('user')
                    ->where('id', $post['id'])
                    ->update(
                        [
                            'truename' => $post['truename'],
                            'email' => $post['email'],
                            'mobile' => $post['mobile'],
                            'token' => $post['token']
                        ]);
            } else {
                $validate = validate('User');
                $res = $validate->scene('editPassword')->check($post);
                if ($res !== true) {
                    $this->error($validate->getError());
                }
                $data['truename'] = $post['truename'];
                $data['password'] = md5($post['password']);
                $data['mobile'] = $post['mobile'];
                $data['email'] = $post['email'];
                $data['token'] = $post['token'];
                Db::name('user')
                    ->where('id', $post['id'])
                    ->update($data);
            }
            session('truename', $post['truename']);
            $this->success('修改成功');
        } else {
            $data = Db::name('User')
                ->where('id', isession('user_id'))
                ->find();
            $this->assign('data', $data);
            //获取公司信息
            $info = DB::name("company")->where('id', $this->session['company_id'])->find();
            !empty($info['use_capacity']) && $info['use_capacity'] = diskTransform($info['use_capacity']);
            $this->assign('info', $info);
            return $this->fetch('info');
        }
    }

    /**
     * 添加子公司
     */
    public function addCompany()
    {
        if (post()) {
            $post = post();
            $validate = validate('User');
            if ($validate->check($post) !== true) {
                $this->error($validate->getError());
            }
            $res = Db::name('user')
                ->where('username', $post['username'])
                ->find();
            if (checkArr($res)) {
                $this->error('该用户已存在');
            }

            $data['username'] = $post['username'];
            $data['truename'] = $post['truename'];
            $data['password'] = md5($post['password']);
            $data['email'] = $post['email'];
            $data['type'] = 2;
            $data['status'] = 1;
            $data['last_login_ip'] = '0.0.0.0';
            $data['create_time'] = date('Y-m-d H:i:s', time());
            $data['super'] = $this->session['super'] + 1;
            $data['pid'] = $this->session['user_id'];
            $data['role_id'] = $post['group_id'];
            $data['from'] = isset($this->session['from']) ? $this->session['from'] . "," . $this->session['user_id'] : $this->session['user_id'];
            $data['company_id'] = $this->session['company_id'];

            Db::name('company')->insert(['name' => $post['company'], 'upload_capacity' => $post['upload_capacity']]);
            $data['company_id'] = Db::name('company')->getLastInsID();

            Db::name('user')->insert($data);
            $this->success('添加成功');
        } else {
            $where['flag'] = 1;
            $where['creater_id'] = $this->session['user_id'];
            $where['company_id'] = $this->session['company_id'];
            $where['id'] = ['neq', $this->session['role_id']];
            $where['concierge'] = 1;
            $where['type'] = 2;
            $where['status'] = 1;
            $role = Db::name('auth_group')
                ->where($where)
                ->order('sort asc')
                ->select();

            $this->assign('type', $this->session['type']);
            $this->assign('auth_group', $role);
            return $this->fetch('addCompany');
        }
    }

}
